package com.ssyu.examination.questionbank.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.commons.lang3.StringUtils;

import com.ssyu.examination.conmmon.App;
import com.ssyu.examination.conmmon.AppServlet;
import com.ssyu.examination.conmmon.Constants;
import com.ssyu.examination.conmmon.PageModel;
import com.ssyu.examination.conmmon.util.DBUtil;
import com.ssyu.examination.conmmon.util.FastjsonUtil;
import com.ssyu.examination.questionbank.entity.QuestionQesEntity;
import com.ssyu.examination.questionbank.service.QuestionQesService;
import com.ssyu.examination.system.entity.CourseEntity;

@WebServlet("/QuestionQesServlet")
@MultipartConfig
public class QuestionQesServlet extends AppServlet {
	private static final long serialVersionUID = 1L;

	public QuestionQesServlet() {
		super();
	}

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding(Constants.ENCODE_UTF8);
		String command = request.getParameter("command");
		if ("listQuestion".equals(command)) {
			listQuestion(request, response);
		} else if ("getQuestion".equals(command)) {
			getQuestion(request, response);
		} else if ("updateQuestion".equals(command)) {
			updateQuestion(request, response);
		} else if ("deleteQuestion".equals(command)) {
			deleteQuestion(request, response);
		} else if ("changeQuestion".equals(command)) {
			changeQuestion(request, response);
		} else if ("addQuestion".equals(command)) {
			addQuestion(request, response);
		} else if ("listCourse".equals(command)) {
			listCourse(request, response);
		} 
	} 
	
	private void listCourse(HttpServletRequest request, HttpServletResponse response) {
		List<CourseEntity> courseList = DBUtil.executeQuery(CourseEntity.class, 
				"SELECT * FROM sys_course");
		
		print(response, FastjsonUtil.toJsonWithDateFormat(courseList,
				"yyyy-MM-dd HH:mm:ss"));
	}

	/**
	 * 试题新增
	 * @param request
	 * @param response
	 * @throws ServletException 
	 * @throws IOException 
	 */
	private void addQuestion(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		String question = request.getParameter("addName");
		String attachment = request.getParameter("addAttachment");
//		Part part = request.getPart("addAttachment");
//		String [] split = part.getSubmittedFileName().split("\\\\");
//		String fileName = split[split.length - 1];
//		part.write(getServletContext().getRealPath("/upload/") + fileName);
//		System.out.println(part.getSize());
//		File file = new File(getServletContext().getRealPath("/upload/") + fileName);
		int questionType = Integer.parseInt(request.getParameter("addType"));
		String answerA = request.getParameter("addAnswerA");
		String answerB = request.getParameter("addAnswerB");
		String answerC = request.getParameter("addAnswerC");
		String answerD = request.getParameter("addAnswerD");
		String answer = request.getParameter("addAnswer");
		int difficulty = Integer.parseInt(request.getParameter("addDifficulty"));
		String analysis = request.getParameter("addAnalysis");
		String keywords = request.getParameter("addKeywords");
		int operateId = App.getOperateId(request, response);
		int courseId = Integer.parseInt(request.getParameter("addCourse"));
		int row = DBUtil.executeUpdate(
				"INSERT INTO qes_qestions VALUES(NULL, ?, ?, ?,?,?,?,?,?,?,?,?,?,?,NOW() , 1,NULL)",
				question,attachment,questionType,courseId,answerA,answerB,answerC,answerD,answer,difficulty,analysis,keywords,operateId);

		if (row == 1) {
			print(response, 1);
		}
	}

	/**
	 * 修改试题状态
	 * @param request
	 * @param response
	 */
	private void changeQuestion(HttpServletRequest request, HttpServletResponse response) {
		int id = Integer.parseInt(request.getParameter("id"));

		QuestionQesEntity questionQesEntity = DBUtil.getUniqueResult(QuestionQesEntity.class, "select * from qes_qestions where id=?", id);
		int state = questionQesEntity.getState();
		if (state == 1) {
			state = 2;
		} else {
			state = 1;
		}
		int row = DBUtil.executeUpdate("update qes_qestions set state=? where id=? ", state, id);
		if (row == 1) {
			print(response, 1);
		}
	}

	/**
	 * 删除试题信息
	 * @param request
	 * @param response
	 */
	private void deleteQuestion(HttpServletRequest request, HttpServletResponse response) {
		String ids = request.getParameter("ids");
		int row = DBUtil.executeUpdate("DELETE FROM qes_qestions WHERE id IN (" + ids
				+ ")");

		if (row >= 1) {
			print(response, 1);
		}
	}

	/**
	 * 修改试题信息
	 * @param request
	 * @param response
	 */
	private void updateQuestion(HttpServletRequest request, HttpServletResponse response) {
		int id = Integer.parseInt(request.getParameter("id"));
		String question = request.getParameter("updateName");
		String attachment = request.getParameter("updateAttachment");
		int questionType = Integer.parseInt(request.getParameter("questionTypeUpdate"));
		int courseId = Integer.parseInt(request.getParameter("questionCourseUpdate"));
		String answerA = request.getParameter("updateAnswerA");
		String answerB = request.getParameter("updateAnswerB");
		String answerC = request.getParameter("updateAnswerC");
		String answerD = request.getParameter("updateAnswerD");
		String answer = request.getParameter("updateAnswer");
		int difficulty = Integer.parseInt(request.getParameter("questionDifficultyUpdate"));
		String analysis = request.getParameter("updateAnalysis");
		String keywords = request.getParameter("updateKeywords");
		
		
		int row = DBUtil.executeUpdate("UPDATE qes_qestions SET question=?,attachment=?,question_type=?,course_id=?,answer_a=?,"
				+ "answer_b=?,answer_c=?,answer_d=?,answer=?,difficulty=?,analysis=?,keywords=? WHERE id=?", 
				question,attachment,questionType,courseId,answerA,answerB,answerC,answerD,answer,difficulty,analysis,keywords,id);
		if (row == 1) {
			print(response, 1);
		}
	}

	
	/**
	 * 获取试题信息
	 * @param request
	 * @param response
	 */
	private void getQuestion(HttpServletRequest request, HttpServletResponse response) {
		int id = Integer.parseInt(request.getParameter("id"));

		QuestionQesEntity question = DBUtil.getUniqueResult(QuestionQesEntity.class,
				"SELECT * FROM qes_qestions WHERE id=?", id);

		if (question != null) {
			print(response, FastjsonUtil.toJson(question));
		}
	}

	/**
	 * 分页列举试题信息
	 * 
	 * @param request
	 * @param response
	 */
	private void listQuestion(HttpServletRequest request, HttpServletResponse response) {
		int page = Integer.parseInt(request.getParameter("page"));
		int rows = Integer.parseInt(request.getParameter("rows"));
		String question = request.getParameter("questionName");
		
		String questionTypeStr = request.getParameter("questionType");
		int questionType = 0;
		if (StringUtils.isNotBlank(questionTypeStr)) {
			questionType = Integer.parseInt(questionTypeStr);
		}
		
		String difficultyStr = request.getParameter("difficulty");
		int difficulty = 0;
		if (StringUtils.isNotBlank(difficultyStr)) {
			difficulty = Integer.parseInt(difficultyStr);
		}
		
		String courseStr = request.getParameter("questionCourse");
		int courseId = 1;
		if (StringUtils.isNotBlank(courseStr)) {
			courseId = Integer.parseInt(courseStr);
		}
		String stateStr = request.getParameter("state");
		int state = 1;
		if (StringUtils.isNotBlank(stateStr)) {
			state = Integer.parseInt(stateStr);
		}
		
		PageModel<QuestionQesEntity> pageModel = QuestionQesService.listQuestion(page, rows,
				question,questionType,courseId,difficulty,state);
		print(response, FastjsonUtil.toJsonWithDateFormat(pageModel,
				"yyyy-MM-dd HH:mm:ss"));	
//		System.out.println(FastjsonUtil.toJsonWithDateFormat(pageModel,
//				"yyyy-MM-dd HH:mm:ss"));
	}

}
